package com.lablzh.gdxy.controller;

import com.lablzh.gdxy.component.UserDetailsUtil;
import com.lablzh.gdxy.entity.Student;
import com.lablzh.gdxy.entity.design.Design;
import com.lablzh.gdxy.entity.design.DesignApply;
import com.lablzh.gdxy.entity.design.StudentDesign;
import com.lablzh.gdxy.repository.design.DesignRepository;
import com.lablzh.gdxy.service.DesignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/design")
public class DesignController {

    @Autowired
    private UserDetailsUtil userDetailsUtil;

    @Autowired
    private DesignService designService;

    @Autowired
    private DesignRepository designRepository;

//    @GetMapping("/getCourseParametersBy")

    /**
     * 多条件组合查询毕业设计,；类别，名称，学院，教师，年纪
     */
    //是否加入
    @PreAuthorize("hasAnyRole('admin', 'teacher','student')")
    @PostMapping("/queryDesign")
    public Map queryDesign(@RequestBody Design design, @RequestParam("page") Integer page) {
//        System.out.println(design);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("category",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("college", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("teacherUsername", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("grade", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<Design> example = Example.of(design, exampleMatcher);
//        Pageable page = PageRequest.of(page, 20, Sort.by(Sort.Direction.DESC, "id"));
        Pageable designPage = PageRequest.of(page - 1, 20,Sort.by(Sort.Direction.DESC, "id"));
        Page<Design> all = designRepository.findAll(example, designPage);
        Map<String, Object> data = new HashMap<>();
        data.put("totalPage",all.getTotalPages());
        data.put("total", all.getTotalElements());
        data.put("design", all.getContent());
        return data;
    }

    /**
     * 有问题
     * 申请创建毕业设计
     *
     * @param design
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PostMapping("/team")
    public String applyCreate(@RequestBody Design design) {
        design.setAudit("未审");
        return designService.applyCreate(design);
    }

    /**
     * 更新毕业设计信息
     *
     * @param design
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/team")
    public String updateTeam(@RequestBody Design design) {
        design.setAudit("未审");
        return designService.updateTeam(design);
    }

    /**
     * 根据毕设id获取毕设信息
     *
     * @param id
     * @return
     */
    @GetMapping("/teamById")
    public Design getTeamById(@RequestParam("ID") Integer id) {
        return designService.getTeamById(id);
    }

    /**
     * 获取所有毕业设计
     *
     * @return
     */

    @GetMapping("/team")
    public List<Design> getAllTeam() {
        return designService.getAllTeam();
    }

    /**
     * 根据id删除课设
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @DeleteMapping("/team")
    public String deleteTeam(@RequestParam("ID") Integer id) {
        return designService.deleteTeam(id);
    }

    /**
     * 根据审核情况获取毕业设计
     *
     * @param audit
     * @return
     */
    @GetMapping("/audited")
    public Object getAudited(@RequestParam("audit") String audit, @RequestParam("page") Integer page) {
        System.out.println("!!!!!!!!!!!!!");
        System.out.println(audit);
        Map<String, Object> map = new HashMap<>();
        if (page != -1) {
            Page<Design> audited = designService.getAudited(audit, page, 20);
            System.out.println(audited);
            map.put("total", audited.getTotalElements());
            map.put("design", audited.getContent());
            map.put("totalPage", audited.getTotalPages());
            return map;
        }
        List<Design> audited = designService.getAudited(audit);
        map.put("design", audited);
        return map;
    }

    @GetMapping("/designpage")
    public Object getAllTeacher(@RequestParam("page") Integer pagenum) {
        Page<Design> page = designService.queryDesignSelective(pagenum, 20);
        //查询结果总行数
        System.out.println(page.getTotalElements());
        //按照当前分页大小，总页数
        System.out.println(page.getTotalPages());
        //按照当前页数、分页大小，查出的分页结果集合
       /* for (Goods goods: page.getContent()) {
            System.out.println(goods.toString());
        }*/
        System.out.println("-------------------------------------------");
        List<Design> designs = page.getContent();
        Long total = page.getTotalElements();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("design", designs);
        data.put("totalpage", page.getTotalPages());
        return data;
    }

    /**
     * 获取某教师的毕业设计
     *
     * @return
     */
    @GetMapping("/teamTeacher")
    public List<Design> teamTeacher() {
        return designService.teamTeacher();
    }

    /**
     * 修改开放状态
     *
     * @param id
     * @param status
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/updateStatus")
    public String updateStatus(@RequestParam("ID") Integer id, @RequestParam("status") String status) {
        return designService.updateStatus(id, status);
    }

    /**
     * 修改审核情况
     *
     * @param id
     * @param audit
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/updateAudit")
    public String updateAudit(@RequestParam("ID") Integer id, @RequestParam("audit") String audit) {
        return designService.updateAudit(id, audit);
    }

    @PostMapping("/task")
    public Map<String, String> addTask(HttpServletRequest request) throws IOException {
        String category = request.getParameter("category");
        Integer id = Integer.valueOf(request.getParameter("ID"));
        return designService.addTask(category, id, request);
    }

    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/auditTask")
    public String auditTask(@RequestParam("ID") Integer id, @RequestParam("taskAudit") String taskAudit) {
        return designService.auditTask(id, taskAudit);
    }

    /**
     * 学生申请毕业设计
     *
     * @param id
     * @return
     */
    @PostMapping("/apply")
    public String apply(@RequestParam("ID") Integer id) {
        return designService.apply(id);
    }

    /**
     * 撤销申请
     * @param id
     * @return
     */
    @DeleteMapping("/undo")
    public String undo(@RequestParam("ID") Integer id) {
        return designService.undo(id);
    }

    /**
     * 教师获取申请表
     *
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @GetMapping("/applyTeacher")
    public List<DesignApply> applyTeacher(@RequestParam("ID") Integer id) {
        return designService.applyTeacher(id);
    }

    /**
     * 学生查看自己的申请
     * @return
     */
    @GetMapping("/applyStudent")
    public List<DesignApply> applyStudent() {
        return designService.applyStudent();
    }

    /**
     * 审核通过
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/confirm")
    public String confirm(@RequestParam("ID") Integer id) {
        return designService.confirm(id);
    }

    /**
     * 退回重选
     *
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/refuse")
    public String refuse(@RequestParam("ID") Integer id) {
        return designService.refuse(id);
    }

    /**
     * 直接删除学生申请
     */
    @PreAuthorize("hasAnyRole('teacher', 'admin')")
    @DeleteMapping("/deleteStudent")
    public String deleteStudent(@RequestParam("id") Integer id) {
        return designService.deleteStudent(id);
    }

    /**
     * 学生获取自己的毕业设计
     *
     * @return
     */
    @GetMapping("/designStudent")
    public List<StudentDesign> getDesignStudent() {
        return designService.getDesignStudent();
    }

    /**
     * 获取某毕业设计所有学生
     *
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @GetMapping("/studentsChoosed")
    public List<StudentDesign> getChoosed(@RequestParam("ID") Integer id) {
        return designService.getChoosed(id);
    }


    /**
     * 上传毕设相关报告
     *
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadReport")
    public Map<String, String> uploadReport(HttpServletRequest request) throws IOException {
        String category = request.getParameter("category");
        Integer id = Integer.valueOf(request.getParameter("ID"));//这里是毕设表id
        return designService.uploadReport(request, category, id);
    }

    /**
     * 批阅报告
     * @param id
     * @param type            报告类型
     * @param studentUsername
     * @param score
     * @param level
     * @param note
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/review")
    public String review(
            @RequestParam("designID") Integer id,
            @RequestParam("type") String type,
            @RequestParam("studentUsername") String studentUsername,
            @RequestParam("score") Integer score,
            @RequestParam("level") String level,
            @RequestParam("note") String note) {
        return designService.review(id, type, studentUsername, score, level, note);
    }

    /**
     * 根据英文翻译提交情况
     *
     * @param summit
     * @param id
     * @return
     */
    @GetMapping("/studentByTransSummit")
    public List<StudentDesign> getStudentByTransSummit(@RequestParam("summit") String summit,
                                                       @RequestParam("ID") Integer id) {
        return designService.getStudentByTransSummit(summit, id);
    }

    @GetMapping("/studentByTransReview")
    public List<StudentDesign> getStudentByTransReview(@RequestParam("review") String review,
                                                       @RequestParam("ID") Integer id) {
        return designService.getStudentByTransReview(review, id);
    }

    @GetMapping("/studentByReportSummit")
    public List<StudentDesign> getStudentByReportSummit(@RequestParam("summit") String summit,
                                                        @RequestParam("ID") Integer id) {
        return designService.getStudentByReportSummit(summit, id);
    }

    @GetMapping("/studentByReportReview")
    public List<StudentDesign> getStudentByReportReview(@RequestParam("review") String review,
                                                        @RequestParam("ID") Integer id) {
        return designService.getStudentByReportReview(review, id);
    }

    @GetMapping("/studentByPaperSummit")
    public List<StudentDesign> getStudentByPaperSummit(@RequestParam("summit") String summit,
                                                       @RequestParam("ID") Integer id) {
        return designService.getStudentByPaperSummit(summit, id);
    }

    @GetMapping("/studentByPaperReview")
    public List<StudentDesign> getStudentByPaperReview(@RequestParam("review") String review,
                                                       @RequestParam("ID") Integer id) {
        return designService.getStudentByPaperReview(review, id);
    }


    /**
     * 获取报告成绩
     * @return
     */
    @PreAuthorize("hasAnyRole('admin','teacher')")
    @PostMapping("/queryPerformance")
    public Map<String,Object> export(@RequestBody StudentDesign studentDesign,@RequestParam("page")int page) {
        return designService.queryPerformance(studentDesign,page);
    }

    /**
     * 下载成绩报表
     * @param request
     * @param response
     * @return
     * @throws FileNotFoundException
     */
    @PreAuthorize("hasAnyRole('admin','teacher')")
    @PostMapping("/downloadExcel")
    public void downloadExcel(@RequestBody StudentDesign studentDesign,
                              HttpServletRequest request,
                              HttpServletResponse response,
                              @RequestParam("sort") String sort) throws FileNotFoundException {
        designService.downloadExcel(studentDesign, request, response, sort);
    }

    /**
     * 下载互选情况表
     * @param type
     * @param college
     * @param major
     * @param grade
     * @param response
     * @param request
     * @return
     * @throws FileNotFoundException
     */
    @PreAuthorize("hasAnyRole('admin','teacher')")
    @GetMapping("/downloadChoose")
    public void downloadChoose(@RequestParam("type") String type,
                               @RequestParam("college") String college,
                               @RequestParam("major") String major,
                               @RequestParam("grade") String grade,
                               HttpServletResponse response,
                               HttpServletRequest request
    ) throws FileNotFoundException {
        System.out.println("学生互选下载");
        designService.downloadChoose(type, college, major, grade, request, response);
    }

    /**
     * 导出题目互选情况表
     * @param college
     * @param grade
     * @param response
     * @param request
     * @return
     * @throws FileNotFoundException
     */
    @PreAuthorize("hasAnyRole('admin','teacher')")
    @GetMapping("/downloadDesign")
    public void downloadDesign(@RequestParam("college") String college,
                               @RequestParam("grade") String grade,
                               HttpServletResponse response,
                               HttpServletRequest request) throws FileNotFoundException {
        designService.downloadDesign(college, grade, request, response);

    }

    /**
     * 根据专业下载课题安排表
     * @param college
     * @param major
     * @param grade
     * @param sortMethod
     * @param response
     * @param request
     * @return
     * @throws FileNotFoundException
     */
    @PreAuthorize("hasAnyRole('admin','teacher')")
    @GetMapping("/downloadArrangeByMajor")
    public void downloadArrangeByMajor(@RequestParam("college") String college,
                                       @RequestParam("major") String major,
                                       @RequestParam("grade") String grade,
                                       @RequestParam("sortMethod") String sortMethod,
                                       @RequestParam("department") String department,
                                       HttpServletResponse response,
                                       HttpServletRequest request) throws FileNotFoundException {
        System.out.println("按专业下载");
        designService.downloadArrangeByMajor(college, major, department, grade, sortMethod, request, response);
    }

    @PreAuthorize("hasAnyRole('admin','teacher')")
    @GetMapping("/downloadArrange")
    public void dowloadArrange(@RequestParam("college") String college,
                               @RequestParam("grade") String grade,
                               HttpServletResponse response,
                               HttpServletRequest request) throws FileNotFoundException {
        designService.dowloadArrange(college, grade, response, request);

    }

}
